<template>
  <div class="user">
    <div class="user-left">
      <div class="user-left-head">
        <div>
          <el-input placeholder="搜索" v-model="name" @focus="hideUsers" @clear="showUsers" @input="searchFriend" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
        <span title="添加朋友" class="iconfont icon-user-add" @click="searchUser"></span>
      </div>
      <div v-if="usersVisible">
        <div :class="selectItem===0?'user-left-item user-left-item-active':'user-left-item'" @click="select(0)">
          <el-badge :value="unreadMsgSum" :hidden="unreadMsgSum === 0 ? true : false">
            <div class="user-left-item-avatar iconfont icon-new-friend" style="background-color: #fa9d3b;"></div>
          </el-badge>
          <div class="user-left-item-name">新的朋友</div>
        </div>
        <div :class="selectItem===user.id?'user-left-item user-left-item-active':'user-left-item'" v-if="user.id !== currentUser.id" v-for="user in users" :key="user.id" @click="selectUser(user)">
          <img class="user-left-item-avatar" :src="user.avatar">
          <div class="user-left-item-name">{{user.comment}}</div>
        </div>
      </div>
      <div v-else>
        <div :class="selectItem===user.id?'user-left-item user-left-item-active':'user-left-item'" v-for="user in searchResult" :key="user.id" @click="showDialog(user)">
          <img class="user-left-item-avatar" :src="user.avatar">
          <div class="user-left-item-name">{{user.nickname}}</div>
        </div>
      </div>
    </div>
    <div class="user-right" v-if="selectItem===0" @click="readMessage">
      <div class="user-right-head"><span>新的朋友</span></div>
      <div class="user-right-request">
        <div class="user-right-request-item" v-for="(message,i) in messageArr" :key="i">
          <img :src="message.avatar" class="user-right-request-item-avatar">
          <div class="user-right-request-item-info">
            <span class="user-right-request-item-info-name">{{message.nickname}}</span>
            <span class="user-right-request-item-info-intro">{{message.introduction}}</span>
          </div>
          <button v-if="message.accept === 0" @click="acceptRequest(message)">接受</button>
          <span v-else style="color: #999999;font-size: 13px">已添加</span>
        </div>
      </div>
    </div>
    <div class="user-information" v-else>
      <div>
        <user-info ref="userInfo" :id="user.id"></user-info>
      </div>
    </div>
    <el-dialog title="申请添加朋友" :visible.sync="dialogVisible">
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <el-form-item label="简介" prop="introduction" style="margin-bottom: 20px">
          <el-input v-model="form.introduction"></el-input>
        </el-form-item>
        <el-form-item label="备注名" prop="comment">
          <el-input v-model.number="form.comment"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitForm('form')" size="mini">提交</el-button>
        <el-button @click="dialogVisible = false" size="mini">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import UserInfo from './UserInfo'
export default({
  name: 'User',
  created () {
    this.users = this.$store.state.users
    this.select(0)
  },
  data () {
    return {
      name: '',
      num: 5,
      users: [],
      user: {},
      searchResult: [],
      currentUser: this.$store.state.currentUser,
      selectItem: 0,
      dialogVisible: false,
      form: {
        comment: '',
        introduction: '',
        friendId: 0,
        userId: 0
      },
      rules: {
        introduction: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        comment: [
          { required: true, message: '请输入备注名', trigger: 'blur' }
        ]
      },
      usersVisible: true
    }
  },
  methods: {
    select (index) {
      this.selectItem = index
      this.readMessage()
    },
    showDialog (user) {
      this.dialogVisible = true
      this.form.friendId = user.id
      this.form.userId = this.$store.state.currentUser.id
    },
    hideUsers () {
      this.usersVisible = false
    },
    showUsers () {
      this.searchResult = []
      this.usersVisible = true
    },
    searchUser () {
      if (!this.usersVisible) {
        let params = new URLSearchParams()
        params.append('name', this.name)
        this.axios.post('/api/v1/user/searchUser', params).then((response) => {
          if (response.data.code === 1) {
            this.searchResult = response.data.data
          } else {
            this.$message({
              message: response.data.message,
              type: 'error'
            })
          }
        }).catch((error) => {
          this.$message({
            message: error,
            type: 'error'
          })
          console.log(error)
        })
      }
    },
    searchFriend () {
      if (!this.usersVisible) {
        let params = new URLSearchParams()
        params.append('name', this.name)
        params.append('userId', this.$store.state.currentUser.id)
        this.axios.post('/api/v1/friend/search', params).then((response) => {
          if (response.data.code === 1) {
            this.searchResult = response.data.data
          } else {
            this.$message({
              message: response.data.message,
              type: 'error'
            })
          }
        }).catch((error) => {
          this.$message({
            message: error,
            type: 'error'
          })
          console.log(error)
        })
      }
    },
    selectUser (user) {
      this.selectItem = user.id
      this.user = user
      this.$refs.userInfo.loadUserInfo(user.id)
    },
    sendMessage (id) {
      this.$store.commit('setSelectedItem', 0)
      this.$router.push({name: 'Chat', params: {id}})
    },
    // 提交朋友申请表单
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 表单验证通过，提交表单
          this.axios.post('/api/v1/friend/add', this.form).then((response) => {
            if (response.data.code === 1) {
              this.$message.success('成功提交申请!')
              this.$refs[formName].resetFields()
              this.dialogVisible = false
            } else {
              this.$message({
                message: response.data.message,
                type: 'error'
              })
            }
          }).catch((error) => {
            this.$message({
              message: error,
              type: 'error'
            })
            console.log(error)
          })
        }
      })
    },
    readMessage () {
      let friendRequestMsgArr = this.$store.state.friendRequestMsgArr
      for (let i = 0; i < friendRequestMsgArr.length; i++) {
        friendRequestMsgArr[i].read = 1
      }

      this.$store.commit('setFriendRequestMsgArr', friendRequestMsgArr)
    },
    // 接受好友申请
    acceptRequest (message) {
      this.$prompt('备注名', '通过朋友验证', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: message.introduction
      }).then(({ value }) => {
        let params = new URLSearchParams()
        params.append('friendId', message.senderId)
        params.append('userId', message.receiverId)
        params.append('comment', value)
        this.axios.post('/api/v1/friend/agree', params).then((response) => {
          if (response.data.code === 1) {
            this.$message.success('已经通过验证！')
            // 去开启新的会话
            message.comment = value
            message.chatType = 0
            this.addConversation(message)
            this.addUser(message)
            // 更新消息状态
            message.accept = 1
          } else {
            this.$message.error(response.data.message)
          }
        }).catch((error) => {
          this.$message.error(error)
          console.log(error)
        })
      }).catch(() => {
      })
    },
    // 添加会话
    addConversation (message) {
      let conversation = {
        id: message.senderId,
        avatar: message.avatar,
        comment: message.comment,
        chatType: message.chatType,
        unreadMsgSum: 0,
        input: '',
        messages: [
          {
            id: new Date().getTime(),
            type: 0,
            chatType: message.chatType,
            senderAvatar: message.avatar,
            senderId: message.senderId,
            receiverId: message.receiverId,
            date: new Date(),
            content: message.introduction,
            status: 1
          }
        ]
      }
      let conversations = this.$store.state.conversations
      conversations.unshift(conversation)
      this.$store.commit('setConversations', conversations)
      this.$store.commit('setSelectedConversation', conversation)
    },
    // 向好友数组添加好友
    addUser (message) {
      let user = {id: message.senderId, avatar: message.avatar, comment: message.comment}
      this.users.unshift(user)
      this.$store.commit('setUsers', this.users)
    }
  },
  components: {
    UserInfo
  },
  computed: {
    messageArr () {
      return this.$store.state.friendRequestMsgArr
    },
    unreadMsgSum () {
      let friendRequestMsgArr = this.$store.state.friendRequestMsgArr
      let sum = 0
      for (let i = 0; i < friendRequestMsgArr.length; i++) {
        if (friendRequestMsgArr[i].read === 0) {
          sum++
        }
      }
      return sum
    }
  }
})
</script>
<style lang="stylus" rel="stylesheet/stylus">
.v-modal
  background none
.user-left
  position fixed
  top 55px
  left 55px
  bottom 0
  width 250px
  overflow auto
  background-color #e4e5e6
  &::-webkit-scrollbar
    display none
  &-head
    position fixed
    top 0
    left 55px
    width 250px
    height 55px
    box-sizing border-box
    padding-top 10px
    padding-left 10px
    background-color #f6f6f6
  &-head > div
    display inline-block
    width 190px
    margin-right 8px
  &-head > span
    display inline-block
    width 25px
    height 25px
    line-height 25px
    font-size 20px
    text-align center
    color #545454
    border-radius 5px
    background-color #e2e2e2
    cursor pointer
  &-item
    display flex
    align-items center
    height 63px
    font-size 14px
    &:hover
      background-color #dcdad9
      cursor default
    &-active
      background-color #c5c5c6
    &-avatar
      width 35px
      height 35px
      line-height 35px
      text-align center
      margin-left 10px
      color white
      border-radius 2px
    &-name
      margin-left 10px
.user-right
  position fixed
  top 55px
  left 305px
  right 0
  bottom 0
  background-color #f5f5f5
  border-left 1px solid #d6d6d6
  overflow auto
  &::-webkit-scrollbar
    display none
  &-head
    position fixed
    top 0
    width 100%
    height 55px
    padding-left 20px
    line-height 55px
    font-size 20px
    background-color #f5f5f5
    border-bottom 1px solid #e7e7e7
  &-request
    display flex
    flex-direction column
    align-items center
    padding-right 80px
    padding-left 80px
    cursor default
    &-item
      display flex
      align-items center
      width 100%
      min-width 220px
      height 80px
      border-bottom 2px solid #e7e7e7
      &-avatar
        width 50px
        height: 50px;
      &-info
        position relative
        flex-grow 1
        flex-shrink 0
        height 50px
        margin-left 10px
        &-name
          display block
          font-size 10px
          margin-top 5px
        &-intro
          display block
          color #999999
          font-size 10px
          margin-top 8px
      &>button
        background-color #1aad19
        flex-grow 0
        width 45px
        height 25px
        color white
        border none
        &:hover
          background-color #129611
          cursor pointer
.user-information
  position fixed
  top 0
  left 305px
  right 0
  bottom 0
  padding 100px 20px
  background-color #f5f5f5
  border-left 1px solid #d6d6d6
  &>div
    width 400px
    margin 0 auto
</style>
